
package controllers;

import models.User;
import play.data.Form;
import play.data.validation.Constraints.Required;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.mvc.Result;

//import controllers.Authentication.Login;

public class Authentication extends Application {

    public static class Login {

        @Required
        public String name;

        @Required
        public String password;

        public String getName() {
            return name;
        }

        public void setName(final String name) {
            this.name = name;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(final String password) {
            this.password = password;
        }

        public String validate() {
            User user = User.authenticate(name, password);
            String result;
            result = (user == null) ? "Invalid credentials" : null;
            return result;
        }

    }
    
    public static Boolean isAdmin() {    	
    	return true; //Application.getUser().getName().equals("admin");    	
    }

    public static Result index() {
        return login();
    }

    /**
     * Login page.
     */
    @Transactional()
    public static Result login() {
        if (request().method() == "GET") {
            return ok(views.html.login.render(play.data.Form.form(Login.class)));
        }

        Form<Login> form = play.data.Form.form(Login.class).bindFromRequest();
        if (form.hasErrors()) {
            flash("error", "Invalid credentials");
            return badRequest(views.html.login.render(form));
        } else {
            String name = form.get().getName();
            String password = form.get().getPassword();
            User user = User.find.byCredential(name, password);

            setUser(user);
            JPA.em().flush();

            flash("success", "You've been logged in");
            return redirect(routes.Application.index());
        }
    }

    /**
     * Logout and clean the session.
     */
    @Transactional()
    public static Result logout() {
        setUser(null);
        flash("success", "You've been logged out");
        return redirect(routes.Application.index());
    }

    @Transactional
    public static Result about() {
        return ok(views.html.help.about.render(""));
    }
}